package com.cnhaimei.vod.util;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.HashSet;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;

public class ImageLoader {
	public final static ImageLoader G = new ImageLoader();
	private final static String TAG = "ImageLoader";
	
	HashMap<String, SoftReference<Bitmap>> mImageBuffer = null;
	private HashSet<String> loadingSet = new HashSet<String>(); 

	public ImageLoader() {
		mImageBuffer = new HashMap<String, SoftReference<Bitmap>>();
	}
	
	/**
	 * Get image from local or network
	 * 
	 * @param name
	 * @param listener
	 * @param context 最好为application Context
	 * @param isCache
	 *            True express come from cache director, False express come from
	 *            SDCard
	 * @return
	 * 
	 * @author Josephluo
	 */
	public Bitmap getBitmap(final ImageTaskListener listener,
			final String name) {

		if (name == null) {
			return null;
		}
		
		SoftReference<Bitmap> ref =  mImageBuffer.get(name);
		Bitmap b = ref != null ? ref.get() : null; 

		if (b != null) {
			return b;
		}

		Object str[] = new Object[4];
		str[0] = name;
		str[1] = listener;
		Log.e(TAG, "img url" + name);
		if (!loadingSet.contains(name)) {
			new CanvasImageTask(false).execute(str);
			loadingSet.add(name);
		} else {
			Log.e(TAG, "img is loading " + name);
		}

		return null;
	}

	public void clearBuffer() {
		mImageBuffer.clear();
	}
	
	public static abstract class ImageTaskListener {
		CanvasImageTask task;
		public void  unListener() {
			if (task != null) {
				task.mListener = null;
			}
		}
		public abstract void onLoadingFinished(Bitmap bitmap, String url);
	}

	
	class CanvasImageTask extends AsyncTask<Object, Void, Bitmap> {
		ImageTaskListener mListener;
//		private Object gView;

		/** According to this URL to down load picture */
		private String name;
		private Context mContext;

		/** Down load and generate bitmap object */
		Bitmap bmp = null;

		/** Whether need write picture to cache */
		private boolean mIsCache = true;

		public CanvasImageTask(boolean isCache) {
			mIsCache = isCache;
		}

		@Override
		protected Bitmap doInBackground(Object... str) {
			// Decode parameters
			name = str[0].toString();
			mListener = (ImageTaskListener)str[1];
			if (mListener != null) {
				mListener.task = this;
			}
//			mContext = (Context) str[2];
			
			// Decode bitmap according special director
			bmp = Util.loadStar(name);

			if (bmp != null) {
				mImageBuffer.put(name, new SoftReference<Bitmap>(bmp));
			}

			return bmp;
		}

		@Override
		protected void onPostExecute(Bitmap bm) {
			boolean b = loadingSet.remove(name);
			if (b) {
				Log.e(TAG, "remove loading set:  " + name);
			}
			if (mListener != null) {
				mListener.onLoadingFinished(bm, name);
			}
		}
	}
}
